package edu.neu.agv_backend.remote;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.client.RestClientException;
import lombok.extern.slf4j.Slf4j;
import edu.neu.agv_backend.exception.BusinessException;

@Slf4j
@Component
public class RemoteClient {

    private final RestTemplate restTemplate;

    private final String baseUrl;

    public RemoteClient(RestTemplate restTemplate, @Value("${agv.remote.base-url}") String baseUrl) {
        this.restTemplate = restTemplate;
        this.baseUrl = baseUrl;
    }

    public <T> ResponseEntity<T> get(String path, Class<T> type) {
        return exchange(path, HttpMethod.GET, null, type);
    }

    public <T> ResponseEntity<T> post(String path, Object body, Class<T> type) {
        return exchange(path, HttpMethod.POST, body, type);
    }

    public <T> ResponseEntity<T> put(String path, Object body, Class<T> type) {
        return exchange(path, HttpMethod.PUT, body, type);
    }

    public <T> ResponseEntity<T> delete(String path, Class<T> type) {
        return exchange(path, HttpMethod.DELETE, null, type);
    }

    private <T> ResponseEntity<T> exchange(String path, HttpMethod method, Object body, Class<T> type) {
        String url = baseUrl + path;
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        HttpEntity<Object> entity = new HttpEntity<>(body, headers);
        try {
            log.debug("HTTP {} -> {}", method, url);
            return restTemplate.exchange(url, method, entity, type);
        } catch (RestClientException ex) {
            log.error("Remote call failed: {} {}", method, url, ex);
            throw new BusinessException(502, "Remote call error");
        }
    }
} 